<?php

namespace app\index\controller;
use think\Controller;
use think\Request;
use think\db;
namespace app\mobile\controller;
use think\Controller;
use \Yunpian\Sdk\YunpianClient;


class Index extends Controller
{
   private $app_id = 'wxa2347780b0c307c5';
   private $app_secret = 'c4ef4b4840388e7fcf5ee29c4aed0bd6';
   private $state = 'aaaa';
   // 微信授权
   public function get_authorize_url($redirect_uri = '', $state = '')
   {
          $redirect_uri = urlencode($redirect_uri);
          return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
   }
    // 获取code
    public function wxlogin(){
       $www = 'https://'.$_SERVER['SERVER_NAME']."/mobile/Index/getopenid";
       $autourl = $this->get_authorize_url($www);
       header("location:$autourl");
    }
    // 获取openid
    public function getopenid(){
       if(session('openid')){
       
           return view("Index/invit");
       }  
      
       $code = $_GET['code'];//获取code
       $weixin =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token
       $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
       $array = get_object_vars($jsondecode);//转换成数组
       $openid = $array['openid'];//输出openid
       $where['openid'] = $openid;
       session('openid',$openid);
       $is = db('yao')->where($where)->find();
      
       if($is){
           session('phone',$is['phone']);
           return view("Index/invit");
           echo "已绑定";
       }else{
           $this->assign('openid',$openid);
           return view("Index/bindwx");
           echo "请先绑定手机号码";
       }
    }
    // 请先绑定手机号码
    public function bindwx(){
       // $this->assign('openid',1);
        return view("Index/bindwx");
    }
    public function postbindwx(){
        $data = input('post.');
        $where['phone'] = $data['phone'];
        $datas['openid'] = $data['openid'];
        $is = db('yao')->where($where)->update($datas);
        if($is){
            $msg['code'] = 1;
            $msg['msg'] = "操作成功";
            echo json_encode($msg);die;
        }else{
            $msg['code'] = 0;
            $msg['msg'] = "手机号码不存在";
            echo json_encode($msg);die;
        }
    }
    // 申请提现
    public function tixian(){
        $phone = session('phone');
        $yao = db('yao')->where('phone',$phone)->find();
        $msg['code'] = 0;
        if(!$yao['alipay_aocunt']){
            
            $this->error("请先绑定支付宝",'mobile/Index/bind');
        }
        if($yao['wallet'] <= 0 ){
            $msg['msg'] = "佣金不足";
            $this->error('佣金不足');
        }
        $r = db('yao')->where('phone',$phone)->setDec('wallet', $yao['wallet']);
        $data['yao_id'] = $yao['id'];
        $data['flag'] = 0;
        $data['money'] = $yao['wallet'];
        $data['addtime'] = date('Y-m-d H:i:s');
        $data['type'] = 2;
        $data['phone'] = $yao['phone'];
        $r2 = db('jiesuan')->insert($data);
        if($r && $r){
            $msg['code'] = 200;
            $msg['msg'] = "操作成功";
            $this->success("操作成功");
        }else{
            $msg['msg'] = "操作失败";
            $this->error("操作成功");
        }
        
    }
    public function bindalipay(){
        $alipay = input('post.alipay');
        $phone = session('phone');
        $data['alipay_aocunt'] = $alipay;
        db('yao')->where('phone',$phone)->update($data);
        $msg['msg'] = "操作成功";
        echo json_encode($msg);
        
    }
    public function bind(){
        return view("Index/bind");
    }
    public function detail(){

         return view("Index/detail");
    }
    // 定时任务结算
    public function exejiesuan(){
        $paymoney = 300;
        $list = db('yao')->select();
        foreach ($list as $key => $val){
            $map['phone'] = $val['phone'];
            $users = db('users')->where($map)->find();
           
            if($users['pay_auth_status'] == 1){
                
                $where['yao_id'] = $val['id'];
                
                $res = db('jiesuan')->where($where)->find();
                if(!$res && $val['sj_phone']){
                    $data['yao_id'] = $val['id'];
                    $data['flag'] = 0;
                    $data['money'] = $paymoney;
                    $data['f_money'] = $paymoney-200;
                    $data['addtime'] = date('Y-m-d H:i:s');
                    $data['phone'] = $val['sj_phone'];
                    $data['type'] = 1;
                    db('jiesuan')->insert($data);
                    echo "结算".$val['sj_phone']."用户到jiesuan";
                }
                
            }
        }
        
        $map2['flag'] = 0;
        $jiesuan_list = db('jiesuan')->where($map2)->select();
        foreach ($jiesuan_list as $key => $val){
           $data2['flag'] = 1;
           $where2['id'] = $val['id'];
           db('jiesuan')->where($where2)->update($data2);
           $where3['phone'] = $val['phone'];
           db('yao')->where($where3)->setInc('wallet',$val['f_money']);
           echo "入账用户[".$val['phone']."]";
        }
        
    }
    // 登录页面
    public function login(){

        $phone = input('get.phone');
        $openid = input('get.openid');
        if($phone){
            $res = db('users')->where('phone',$phone)->find();
            if($res){
                session('phone',$res['phone']);
                if($openid){
                     session('openid',$openid);
                }
               
                $yao = db('yao')->where('phone',$phone)->find();
                if(!$yao){ // 如果用户没有邀请码
                    $data['phone'] = $phone;
                    $data['addtime'] = date('Y-m-d H:i:s');
                    $data['code'] = randomkeys(6);
                    db('yao')->insert($data);
                }
                return view("Index/invit");
            }else{
                echo "登录失败，未找到此用户";
            }
        }else{
            echo "登录失败，请返回重试";
        }
       
    }
    public function getuserinfo2(){
        $phone = session('phone');
        
        $list = db('users')->where('phone',$phone)->find();
        
        echo_info(0,'查询成功',count($list),$list);
    }
    // 获取用户基本信息
    public function getuserinfo(){
        $phone = session('phone');
        $list = db('users')->where('phone',$phone)->find();
        $yao = db('yao')->where('phone',$phone)->find();
        $list['img'] = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data="."https://".$_SERVER['SERVER_NAME']."/mobile/Index/register?code=".$yao['code'];
        $list['url'] = "https://".$_SERVER['SERVER_NAME']."/mobile/Index/register?code=".$yao['code'];
        $list['code'] = $yao['code'];
        $list['name'] = $list['name'];
        echo_info(0,'查询成功',count($list),$list);
    }
    // 邀请注册
    public function invit(){
        return view("Index/invit");
    }
    // 截图
    public function yao(){
        return view("Index/yao");
    }

    // 注册页面
    public function register(){
        return view("Index/register");
    }
    // app微信分享页面
    public function reg(){
        
        $phone = $_GET['phone'];
        $yao = db('yao')->where('phone',$phone)->find();
      
        if(!$yao){ // 如果用户没有邀请码
            $data['phone'] = $phone;
            $data['addtime'] = date('Y-m-d H:i:s');
            $data['code'] = randomkeys(6);
            db('yao')->insert($data);
            header("location:/mobile/Index/register?code=".$data['code']);
            die;
        }
        header("location:/mobile/Index/register?code=".$yao['code']);die;
        
    }
    // 注册信息提交
    public function regPost(){
        $yao_code = input('post.yao_code');
        $yao = db('yao')->where('code',$yao_code)->find();
        $msg['msg'] = "发生错误";
        if(!$yao){
            $msg['code'] = 0;
            $msg['msg'] = "邀请码不存在";
            echo_info(0,'查询成功',count($msg),$msg);
        }
        $code = input('post.code');
        $randcode = session('randcode');
        if($code!= $randcode){
            $msg['code'] = 0;
            $msg['msg'] = "短信码不正确";
            echo_info(0,'查询成功',count($msg),$msg);
        }
        $phone = input('post.phone');
        $data['phone'] = $phone;
        $uses = db('users')->where('phone',$yao['phone'] )->find();
        $data['sj_phone'] = $uses['phone'];
        $data['addtime'] = date('Y-m-d H:i:s');
        $data['code'] = randomkeys(6);
        $data['phone_type'] = get_device_type();
        $ip = $_SERVER['REMOTE_ADDR'];
        $data['address'] = zhuanhuanIpAddres($ip);
        $res = db('yao')->insert($data);
        if($res){
            $msg['code'] = 1;
            $msg['msg'] = "注册成功";
            echo_info(0,'查询成功',count($msg),$msg);
        }else{
            $msg['code'] = 0;
            $msg['msg'] = "注册失败";
            echo_info(0,'查询成功',count($msg),$msg);
        }
    }
    // 发送短信
    public function  sendcode(){
        $msg['msg'] = "发送失败";
        $phone = input('post.phone');
        $res = db('users')->where('phone',$phone)->find();
        if($res){
            $msg['msg'] = "号码已经注册";
            echo_info(0,'查询成功',count($msg),$msg);
        }
        $res = db('yao')->where('phone',$phone)->find();
        if($res){
            $msg['msg'] = "号码已经注册";
            echo_info(0,'查询成功',count($msg),$msg);
        }
        $code = rand(1000,9999);
        $apikey = "71c698188ce966b7f9736ed471ae56e7";
        $url = "http://sms.yunpian.com/v2/sms/single_send.json";
        $params = [
            'apikey' => $apikey,
            'mobile' => $phone,
            'text' => "【聆听科技】验证码".$code."。如非本人操作，请忽略本短信",
        ];
        session('randcode', $code);
        $r = send_post($url,$params);
        $r = json_decode($r,true);
        if($r['code'] == 0){
            $msg['msg'] = $r['msg'];
            $msg['code'] = 1;
            echo_info(0,'查询成功',count($msg),$msg);
        }else{
            $msg['msg'] = $r['msg'];
            echo_info(0,'查询成功',count($msg),$msg);
        }
    }
    // 邀请页面数据
    public function myinfo(){
        $phone = session('phone');
        $where['sj_phone'] = $phone;
        $data['haoyou_count'] = db('yao')->where($where)->count(); // 我邀请了多少个好友
        $where2['phone'] = $phone;
        $where2['type'] = 1;
        $where2['flag'] = 1;
        $data['total_money'] = db('jiesuan')->where($where2)->sum('f_money'); // 获得金额
        $wallet = db('yao')->where('phone',$phone)->field('wallet')->find();
       
        if($wallet['wallet']){
            $data['yue'] = 0;
        }else{
            $data['yue'] = $wallet['wallet'];
        }
        $paihang = db('yao')->limit(0,20)->select();
        $ph = [];
        foreach ($paihang as $key => $val){
            $where3['phone'] =  $val['phone'];
            $ph[$key]['yeji'] = db('jiesuan')->where($where3)->sum('f_money');
            $ph[$key]['phone'] = $val['phone'];
            $users = db('users')->where($where3)->find();
            $ph[$key]['nickname'] = $users['nickname'];
            
            $ph[$key]['img'] = $users['portraitUri'];
        }
        rsort($ph);
        $data['ph'] = $ph;
        $data['paiming'] = "暂无排名";
        foreach ($ph as $key => $val){
            if($val['phone'] == $phone){
                $data['paiming'] = $key+1;
            }
        }
        echo_info(0,'查询成功',count($data),$data);
    }
    // 邀请记录
    public function recoed(){
        $phone = session('phone');
        $where['sj_phone'] = $phone;
        $list = db('yao')->where($where)->select();
        foreach ($list as $key => $val){
            $where3['phone'] =  $val['phone'];
            $users = db('users')->where($where3)->find();
            $list[$key]['nickname'] =  $users['nickname'];
            $list[$key]['img'] = str_replace('http','https',$users['portraitUri']);
            $list[$key]['is_merchant'] = $users['is_merchant'];
            $where4['id'] = $val['id'];
            $yao = db('jiesuan')->where($where4)->find();
            if($yao){
                $list[$key]['yueji'] = $yao['f_money'];
            }else{
                $list[$key]['yueji'] = 0;
            }
            
            
        }
        echo_info(0,'查询成功',count($list),$list);
    }
}